use std::sync::Arc;
use anyhow::Result;

use crate::di::{ServiceContainer, services::ConfigService};
use crate::config::{Configs, Server, DataBase, Log, Jwt, Cert};

/// 零动态分发演示
/// 
/// 这个演示展示了我们的系统如何完全避免动态分发，
/// 以及这种设计带来的性能和类型安全优势。

/// 创建演示配置
fn create_demo_config() -> Configs {
    Configs {
        server: Server {
            name: "zero-dispatch-demo".to_string(),
            address: "127.0.0.1:8080".to_string(),
            ssl: false,
        },
        database: DataBase {
            database_url: "sqlite::memory:".to_string(),
        },
        log: Log {
            filter_level: "info".to_string(),
            with_ansi: true,
            to_stdout: true,
            directory: "./logs".to_string(),
            file_name: "zero-dispatch.log".to_string(),
            rolling: "daily".to_string(),
        },
        jwt: Jwt {
            jwt_secret: "zero_dispatch_secret".to_string(),
            jwt_exp: 3600,
        },
        cert: Cert {
            cert: "zero-dispatch.pem".to_string(),
            key: "zero-dispatch.key".to_string(),
        },
    }
}

// ============================================================================
// 零动态分发的具体类型服务
// ============================================================================

/// 数据处理服务 - 具体类型，支持编译器优化
#[derive(Debug)]
pub struct DataProcessor {
    config: Arc<ConfigService>,
    batch_size: usize,
}

impl DataProcessor {
    pub fn new(config: Arc<ConfigService>) -> Self {
        Self {
            config,
            batch_size: 1000,
        }
    }
    
    /// 这个方法可以被编译器内联
    #[inline]
    pub fn process_single(&self, data: u64) -> u64 {
        // 简单的数据处理逻辑
        data * 2 + 1
    }
    
    /// 批量处理 - 编译器可以向量化这个循环
    pub fn process_batch(&self, data: &[u64]) -> Vec<u64> {
        data.iter()
            .map(|&x| self.process_single(x))
            .collect()
    }
    
    /// 复杂处理 - 多个内联函数组合
    #[inline]
    pub fn complex_process(&self, data: u64) -> String {
        let processed = self.process_single(data);
        let server_name = self.get_server_name();
        format!("{}:{}", server_name, processed)
    }
    
    #[inline]
    fn get_server_name(&self) -> &str {
        &self.config.config().server.name
    }
}

/// 缓存服务 - 具体类型，零开销抽象
#[derive(Debug)]
pub struct CacheService {
    config: Arc<ConfigService>,
    processor: Arc<DataProcessor>,
    cache_size: usize,
}

impl CacheService {
    pub fn new(config: Arc<ConfigService>, processor: Arc<DataProcessor>) -> Self {
        Self {
            config,
            processor,
            cache_size: 10000,
        }
    }
    
    /// 缓存查找 - 可以被完全内联
    #[inline]
    pub fn get_or_compute(&self, key: u64) -> u64 {
        // 在真实实现中，这里会有缓存逻辑
        // 这里简化为直接计算
        self.processor.process_single(key)
    }
    
    /// 批量缓存操作 - 编译器可以优化整个调用链
    pub fn get_or_compute_batch(&self, keys: &[u64]) -> Vec<u64> {
        keys.iter()
            .map(|&key| self.get_or_compute(key))
            .collect()
    }
}

/// 聚合服务 - 组合多个具体类型服务
#[derive(Debug)]
pub struct AggregationService {
    cache: Arc<CacheService>,
    processor: Arc<DataProcessor>,
    config: Arc<ConfigService>,
}

impl AggregationService {
    pub fn new(
        cache: Arc<CacheService>,
        processor: Arc<DataProcessor>,
        config: Arc<ConfigService>,
    ) -> Self {
        Self {
            cache,
            processor,
            config,
        }
    }
    
    /// 聚合处理 - 整个调用链都可以被优化
    pub fn aggregate_process(&self, data: &[u64]) -> (Vec<u64>, Vec<String>) {
        let cached_results = self.cache.get_or_compute_batch(data);
        let complex_results = data.iter()
            .map(|&x| self.processor.complex_process(x))
            .collect();
        
        (cached_results, complex_results)
    }
    
    /// 统计信息 - 展示类型安全的组合
    pub fn get_stats(&self) -> ServiceStats {
        ServiceStats {
            server_name: self.config.config().server.name.clone(),
            cache_size: self.cache.cache_size,
            batch_size: self.processor.batch_size,
            total_services: 3,
        }
    }
}

/// 服务统计信息
#[derive(Debug, Clone)]
pub struct ServiceStats {
    pub server_name: String,
    pub cache_size: usize,
    pub batch_size: usize,
    pub total_services: usize,
}

// ============================================================================
// 演示函数
// ============================================================================

/// 演示零动态分发的优势
pub async fn demonstrate_zero_dispatch() -> Result<()> {
    println!("🎯 零动态分发依赖注入演示");
    println!("{}", "=".repeat(50));
    
    // 1. 创建容器并注册服务
    println!("📦 创建服务容器并注册具体类型服务...");
    let container = ServiceContainer::new();
    let config = create_demo_config();
    
    // 注册配置服务
    container.register_singleton::<ConfigService, _>(move |_| {
        Ok(ConfigService::new(config.clone()))
    })?;
    
    // 注册数据处理服务
    container.register_singleton::<DataProcessor, _>(|container| {
        let config = container.resolve::<ConfigService>()?;
        Ok(DataProcessor::new(config))
    })?;
    
    // 注册缓存服务
    container.register_singleton::<CacheService, _>(|container| {
        let config = container.resolve::<ConfigService>()?;
        let processor = container.resolve::<DataProcessor>()?;
        Ok(CacheService::new(config, processor))
    })?;
    
    // 注册聚合服务
    container.register_singleton::<AggregationService, _>(|container| {
        let cache = container.resolve::<CacheService>()?;
        let processor = container.resolve::<DataProcessor>()?;
        let config = container.resolve::<ConfigService>()?;
        Ok(AggregationService::new(cache, processor, config))
    })?;
    
    println!("✅ 所有服务注册完成！");
    
    // 2. 解析具体类型服务
    println!("\n🔍 解析具体类型服务（零动态分发）...");
    
    let processor: Arc<DataProcessor> = container.resolve()?;
    let cache: Arc<CacheService> = container.resolve()?;
    let aggregator: Arc<AggregationService> = container.resolve()?;
    
    println!("✅ 所有服务解析成功，类型: Arc<ConcreteType>");
    
    // 3. 演示编译器优化潜力
    println!("\n⚡ 演示编译器优化潜力...");
    
    // 单次处理 - 可以被内联
    let single_result = processor.process_single(42);
    println!("   单次处理结果: {}", single_result);
    
    // 批量处理 - 可以被向量化
    let batch_data = vec![1, 2, 3, 4, 5];
    let batch_results = processor.process_batch(&batch_data);
    println!("   批量处理结果: {:?}", batch_results);
    
    // 复杂处理 - 多个内联函数组合
    let complex_result = processor.complex_process(100);
    println!("   复杂处理结果: {}", complex_result);
    
    // 4. 演示服务组合
    println!("\n🔗 演示零开销服务组合...");
    
    let test_data = vec![10, 20, 30, 40, 50];
    let (cached, complex) = aggregator.aggregate_process(&test_data);
    
    println!("   缓存结果: {:?}", cached);
    println!("   复杂结果: {:?}", complex);
    
    // 5. 展示类型安全
    println!("\n🛡️ 展示编译时类型安全...");
    
    let stats = aggregator.get_stats();
    println!("   服务统计: {:?}", stats);
    
    // 6. 性能测试
    println!("\n📊 性能测试（1,000,000 次调用）...");
    
    let iterations = 1_000_000;
    let test_value = 12345;
    
    // 测试直接调用性能
    let start = std::time::Instant::now();
    for _ in 0..iterations {
        let _ = processor.process_single(test_value);
    }
    let duration = start.elapsed();
    
    println!("   总耗时: {:.2}ms", duration.as_millis());
    println!("   平均耗时: {:.2}ns", duration.as_nanos() as f64 / iterations as f64);
    println!("   每秒操作数: {:.0}", iterations as f64 / duration.as_secs_f64());
    
    // 7. 内存使用分析
    println!("\n💾 内存使用分析...");
    
    println!("   Arc<DataProcessor>: {} bytes", std::mem::size_of::<Arc<DataProcessor>>());
    println!("   Arc<CacheService>: {} bytes", std::mem::size_of::<Arc<CacheService>>());
    println!("   Arc<AggregationService>: {} bytes", std::mem::size_of::<Arc<AggregationService>>());
    println!("   对比 Arc<dyn Trait>: {} bytes", std::mem::size_of::<Arc<dyn std::fmt::Debug>>());
    
    // 8. 多线程测试
    println!("\n🧵 多线程安全测试...");
    
    let container = Arc::new(container);
    let mut handles = Vec::new();
    
    for i in 0..4 {
        let container_clone = Arc::clone(&container);
        let handle = tokio::spawn(async move {
            let processor = container_clone.resolve::<DataProcessor>().unwrap();
            let result = processor.process_single(i * 100);
            println!("   线程 {} 处理结果: {}", i, result);
            result
        });
        handles.push(handle);
    }
    
    for handle in handles {
        handle.await?;
    }
    
    println!("\n✅ 零动态分发演示完成！");
    println!("{}", "=".repeat(50));
    
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_zero_dispatch_demo() {
        demonstrate_zero_dispatch().await.unwrap();
    }
    
    #[test]
    fn test_concrete_types_size() {
        // 验证具体类型的内存使用
        assert_eq!(std::mem::size_of::<Arc<DataProcessor>>(), 8);
        assert_eq!(std::mem::size_of::<Arc<CacheService>>(), 8);
        
        // 对比 trait 对象
        assert_eq!(std::mem::size_of::<Arc<dyn std::fmt::Debug>>(), 16);
    }
    
    #[test]
    fn test_inlining_potential() {
        let config = create_demo_config();
        let config_service = ConfigService::new(config);
        let processor = DataProcessor::new(Arc::new(config_service));
        
        // 这些调用在 release 模式下可能被完全内联
        let result1 = processor.process_single(42);
        let result2 = processor.process_single(42);
        
        assert_eq!(result1, result2);
        assert_eq!(result1, 85); // 42 * 2 + 1
    }
}
